@file:Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS", "DEPRECATED_IDENTITY_EQUALS")

package com.c.ctgproject.ui.files

import android.Manifest
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.c.ctgproject.R
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.base.BaseApplication
import com.c.ctgproject.mode.MyConstants
import com.c.ctgproject.mode.StorageVehicles
import com.c.ctgproject.mode.VehicleInspection
import com.c.ctgproject.retrofit.Response
import com.c.ctgproject.ui.other.InputPlateActivity
import com.c.ctgproject.ui.newvehicles.Newvehicles
import com.c.ctgproject.ui.vehiclefiles.VehiclefilesActivity
import com.c.ctgproject.ui.vehiclelocation.VehicleLocationActivity
import com.c.ctgproject.ui.vehicleinspection.VehicleInspectionActivity
import com.c.ctgproject.ui.vehicleinspection.VehicleInspectiontActivity
import com.c.ctgproject.utils.*
import com.c.ctgproject.utils.photovideo.takevideo.CameraActivity
import com.c.ctgproject.utils.pickerimage.utils.RequestCode
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.common.Constant
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.jetbrains.anko.startActivity
import java.io.File

/**
 * 档案部 页面
 */
class MainActivity : BaseActivity(), View.OnClickListener {
    private val requestCodeScan = 10001
    private var token: String? = null
    private var mainViewModel: MainViewModel? = null
    private var progressDialog: ProgressDialog? = null
    private var dialogUtils: DialogUtils? = null
    private var builder: AlertDialog.Builder? = null
    private var carPlate: String? = null//车牌号

    override fun getLayout()=R.layout.activity_main

    override fun event() {
        changeTransparentStatusBar()
        token = Utils.getShared2(this, "token")
        dialogUtils = DialogUtils()
        setting.setOnClickListener(this)
        Inputplate_tv.setOnClickListener(this)
        qr_iv.setOnClickListener(this)
        takephoto_iv.setOnClickListener(this)
        mainViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(MainViewModel::class.java)
        //车牌拍照识别回调监听
        mainViewModel!!.getresponsedata().observe(this, Observer { response: Response<*> ->
            progressDialog!!.dismiss()
            if (response.status == 0) {
                mainViewModel!!.getInitialInspectionCar(token!!, response.data.handlerNull())
                carPlate = response.data.handlerNull()
                Log.e("data", response.data.handlerNull())


            } else {
                CustomToast.showToast(this, response.msg)
                //拍照识别错误手动输入车牌
                val intent = Intent(applicationContext, InputPlateActivity::class.java)
                startActivity(intent)
            }
        })

        mainViewModel!!.getStorageVehiclesdata()
            .observe(this, Observer { response: Response<StorageVehicles> ->
                if (response.status == 1) {
                    Toast.makeText(this, response.msg, Toast.LENGTH_LONG).show()
                } else {
                    val intent = Intent(applicationContext, VehicleInspectiontActivity::class.java)
                    intent.putExtra("carPlate", response.data.ownerPlate)
                    startActivity(intent)
                }
            })
        mainViewModel!!.getInitialInspectionCardata()
            .observe(this, { response: Response<VehicleInspection> ->
                if (response.status == 0) {
                    val intent = Intent(applicationContext, VehicleInspectionActivity::class.java)
                    intent.putExtra("carOwner", response.data.carOwner)
                    intent.putExtra("ownerPhone", response.data.ownerPhone)
                    intent.putExtra("ownerPlate", response.data.ownerPlate)
                    intent.putExtra("carId", response.data.carId)
                    intent.putExtra("salesman", response.data.salesman)
                    startActivity(intent)
                } else {
                    builder = AlertDialog.Builder(this@MainActivity).setTitle("提示！").setMessage(response.msg).setPositiveButton("新建车辆") { _, _ ->
                        val intent = Intent(applicationContext, Newvehicles::class.java)
                        intent.putExtra("carPlate", carPlate)
                        startActivity(intent)
                    }.setNegativeButton("取消") { dialogInterface, _ ->
                        dialogInterface.dismiss()
                    }
                    builder!!.create().show()
                }
            })
        //错误回调
        mainViewModel!!.errorMsg.observe(this, Observer {
            progressDialog?.dismiss()
            CustomToast.showToast(this, it)
        })
        //图片视频上传
        mTakePhotoVideo.setOnClickListener {
            scanQr()
        }
    }

    override fun click() {
        //待初验车辆列表
        chuYanIV.setOnClickListener {
            startActivity<FileFirstExamineActivity>()
        }
        //待二验车辆列表
        erYanIV.setOnClickListener {
            startActivity<FileSecondExamineActivity>()
        }
        //拍照列表
        mTakePhotoIV.setOnClickListener {
            startActivity<FileCarWaitPhotographedActivity>()
        }
        //修改车辆信息
        mChangeIV.setOnClickListener {
            startActivity<FileSecondExamineActivity>(MyConstants.CHANGE_CAR_INFO to true)
        }
        //档案管理 手续管理
        mFileManagerIV.setOnClickListener {
            startActivity<FileManagerActivity>()
        }

    }

    override fun onClick(v: View?) {
        //设置
        if (v == setting) {
           showPopupWindow(setting)
        }
        if (v == qr_iv) {
            //二维码 扫码
            val intent = Intent(this@MainActivity, CaptureActivity::class.java)
            startActivityForResult(intent, requestCodeScan)
        }
        if (v == Inputplate_tv) {
            //手动输入车牌号
            val intent = Intent(applicationContext, InputPlateActivity::class.java)
            startActivity(intent)
        }
        //拍照和录像
        if (v == takephoto_iv) {
            //拍照识别车牌
            if ((ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) !== PackageManager.PERMISSION_GRANTED)
                || (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED)
                //增加录音权限
                || (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.RECORD_AUDIO) !== PackageManager.PERMISSION_GRANTED)
            ) {
                Toast.makeText(this, "请在应用管理中打开“相机,录音,读写存储”访问权限！", Toast.LENGTH_LONG).show()
            } else {
                intent = Intent(this@MainActivity, CameraActivity::class.java)
                startActivityForResult(intent, RequestCode.TAKE_PHOTO)
            }
        }
    }

    //拍摄回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RequestCode.TAKE_PHOTO) {
            if (data != null) {
                val filePath = data.getStringExtra("take_photo")
                val file = File(filePath)
                val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
                val part = MultipartBody.Part.createFormData("file", file.name, requestFile)
                progressDialog = ProgressDialog(
                    this@MainActivity,
                    R.style.AppTheme_Dark_Dialog
                )
                progressDialog!!.isIndeterminate = true
                progressDialog!!.setCanceledOnTouchOutside(false)
                progressDialog!!.setCancelable(true)
                progressDialog!!.setMessage("正在识别...")
                progressDialog!!.show()
                Log.d("日志", "开始上传")
                //上传照片
                mainViewModel!!.licensePlate(token!!, file)
            }
        }
        //车辆上传照片和视频
        if (resultCode === Activity.RESULT_OK && requestCode == QR_CODE_RESULT && data != null) {
            val content: String = data.getStringExtra(Constant.CODED_CONTENT)
            MyLog.d("二维码扫描出的信息:$content")
            val strs: List<String> = content.split(":")
            if (strs.size <= 1) {
                Toast.makeText(this, "二维码不包含车牌号信息！", Toast.LENGTH_LONG).show()
            } else {
                if (strs.size <= 1) {
                    Toast.makeText(this, "二维码不包含库位信息！", Toast.LENGTH_LONG).show()
                } else {
                    if (strs[0].replace("\uFEFF", "") == "carCode") {
                        val intent =
                            Intent(applicationContext, FileUploadPhotoVideoActivity::class.java)
                        intent.putExtra("carCode", strs[1])
                        startActivity(intent)
                    } else {
                        Toast.makeText(this, "请扫拓号单二维码！", Toast.LENGTH_LONG).show()
                    }
                }
            }
        }


        // 扫描二维码/条码回传
        if (requestCode === requestCodeScan && resultCode === Activity.RESULT_OK) {
            if (data != null) {
                val content: String = data.getStringExtra(Constant.CODED_CONTENT)
                MyLog.d("二维码扫描出的信息:$content")
                val strs: List<String> = content.split(":")
                if (BaseApplication.getBaseApplication().characterName == "仓储部") {
                    val intent = Intent(applicationContext, VehicleLocationActivity::class.java)
                    if (strs.size <= 1) {
                        Toast.makeText(this, "二维码不包含库位信息！", Toast.LENGTH_LONG).show()
                    } else {
                        if (strs[0].replace("\uFEFF", "") == "carCode") {
                            intent.putExtra("carCode", strs[1])
                            startActivity(intent)
                        } else {
                            Toast.makeText(this, "请扫拓号单二维码！", Toast.LENGTH_LONG).show()
                        }
                    }
                } else {
                    if (strs.size <= 1) {
                        Toast.makeText(this, "二维码不包含车牌号信息！", Toast.LENGTH_LONG).show()
                    } else {
                        if (strs.size <= 1) {
                            Toast.makeText(this, "二维码不包含库位信息！", Toast.LENGTH_LONG).show()
                        } else {
                            if (strs[0].replace("\uFEFF", "") == "carCode") {
                                val intent =
                                    Intent(applicationContext, VehiclefilesActivity::class.java)
                                intent.putExtra("carCode", strs[1])
                                startActivity(intent)
                            } else {
                                Toast.makeText(this, "请扫拓号单二维码！", Toast.LENGTH_LONG).show()
                            }
                        }
                    }
                }
                Log.e("qr", content)
            }
        }
    }


    //双击退出功能
    override fun onBackPressed() {
        exitApp()
    }


}
